const router = require('koa-router')()
const Good=require('../models/goods')

router.prefix('/goods');  //二级路由

//获取到所有的商品信息
router.get('/list', async (ctx, next) => {

    try{
        let allGoods = await Good.find({});
        if(!!allGoods){
            ctx.body={
                code:200,
                msg:"",
                result:allGoods
            }
        }else{
            ctx.body={
                code:300,
                msg:"查询商品信息失败",
                result:""
            }
        }
    }catch(err){
        ctx.body={
            code:400,
            msg:"服务器错误",
            result:""
        }}

})

//添加商品到购物车中
router.post('/toCart', async (ctx, next) => {
    let nowUser;
    let goodsitem =false;
    let nowProductId=ctx.request.body.productId;
    let User = require('../models/users');

    console.log(nowProductId);
    //取出用户
    if(!!ctx.session.user){
        nowUser = await User.findOne({userId:ctx.session.user.userId});

    }else{
        ctx.body={
            code:300,
            msg:"请重新登录",
            result:""
        }
        return ;
    }

    //判断该用户中的购物车中是否有该数据
    for (let item of nowUser.cartList){
        if(item.productId == nowProductId){
            item.productNum++;
            goodsitem=true;
        }
    };
    //没有商品添加
    try{
        if(!goodsitem){
            let addGood = await Good.findOne({productId:nowProductId});
            addGood.productNum=1;
            addGood.checked=1;
            nowUser.cartList.push(addGood);
        }

        let newUserDoc=await nowUser.save();

       if(!! newUserDoc){
           ctx.body={
               code:200,
               msg:"加入购物车成功",
               result:""
           }
       }else{
           ctx.body={
               code:300,
               msg:"加入购物车失败",
               result:""
           }
       }

    }catch(err){
        console.log(err.message)
        ctx.body={
            code:400,
            msg:"服务器错误",
            result:""
        }
    }






})


module.exports = router